<template>
  <div class="designer-core">
    <!-- 顶部标题栏 -->
    <div class="designer-header">
      <div class="header-left">
        <h1>低代码平台</h1>
      </div>
      <div class="header-center">
        <el-button type="primary" @click="handlePreview">
          <el-icon><View /></el-icon>
          预览
        </el-button>
        <el-button type="success" @click="handleSave">
          <el-icon><Download /></el-icon>
          保存
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Upload /></el-icon>
          导出
        </el-button>
      </div>
      <div class="header-right">
        <el-button @click="handleUndo" :disabled="!canUndo">
          <el-icon><RefreshLeft /></el-icon>
          撤销
        </el-button>
        <el-button @click="handleRedo" :disabled="!canRedo">
          <el-icon><RefreshRight /></el-icon>
          重做
        </el-button>
        <el-switch
          v-model="debugMode"
          active-text="调试模式"
          inactive-text="正常模式"
          size="small"
        />
      </div>
    </div>
    
    <div class="designer-main">
      <!-- 左侧组件库 -->
      <div class="component-library">
        <div class="library-header">
          <h3>组件库</h3>
        </div>
        <div class="library-content">
          <div 
            v-for="[categoryName, widgets] in Object.entries(widgetCategories)" 
            :key="categoryName"
            class="category-section"
          >
            <div class="category-title">{{ categoryName }}</div>
            <div class="widget-list">
              <div
                v-for="widget in widgets"
                :key="widget.type"
                class="widget-item"
                draggable="true"
                @dragstart="handleWidgetDragStart(widget, $event)"
                @dragend="handleWidgetDragEnd($event)"
              >
                <div class="widget-icon">
                  <el-icon>
                    <component :is="getWidgetIcon(widget.icon)" />
                  </el-icon>
                </div>
                <div class="widget-info">
                  <div class="widget-name">{{ widget.name }}</div>
                  <div class="widget-description">{{ widget.description }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间画布区域 -->
      <div class="design-canvas">
        <div class="canvas-header">
          <span>设计画布</span>
          <div class="canvas-tools">
            <el-button size="small" @click="clearCanvas">清空画布</el-button>
          </div>
        </div>
        <div 
          class="canvas-content"
          @click="clearSelection"
          @drop="handleComponentDrop"
          @dragover="handleDragOver"
          @dragleave="handleDragLeave"
          @dragenter="handleDragEnter"
        >
          <!-- 测试按钮 - 仅在调试模式下显示 -->
          <div 
            v-if="debugMode" 
            class="debug-tools"
            @dragover="handleDragOver"
            @dragenter="handleDragEnter"
          >
            <el-button 
              size="small" 
              type="primary" 
              @click="testAddComponent"
              style="margin-bottom: 16px; margin-right: 8px;"
            >
              测试添加文本组件
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="testDragAndDrop"
              style="margin-bottom: 16px;"
            >
              测试拖拽功能
            </el-button>
          </div>
          
          <div 
            v-for="component in currentPage?.components || []"
            :key="component.id"
            class="canvas-component"
            :class="{ 'is-selected': isComponentSelected(component) }"
            :style="getCanvasItemStyle(component)"
            @click.stop="handleComponentSelect(component)"
            :data-component-id="component.id"
            :draggable="true"
            @dragstart="handleComponentDragStart(component, $event)"
            @dragend="handleComponentDragEnd($event)"
            @dragover="handleComponentDragOver($event, component)"
            @dragleave="handleComponentDragLeave($event)"
          >
            <ComponentRenderer 
              :component="component"
              :is-selected="isComponentSelected(component)"
              @click="handleComponentSelect"
              @dblclick="editComponent"
              @update="handleComponentUpdate"
              @drop="handleComponentDrop($event, component)"
              @drag-target-highlight="handleDragTargetHighlight"
            />
          </div>
          
          <!-- 空画布提示 -->
          <div 
            v-if="!currentPage?.components?.length" 
            class="empty-canvas"
            @dragover="handleDragOver"
            @dragenter="handleDragEnter"
          >
            <div class="empty-tip">
              <i class="el-icon-plus"></i>
              <p>从左侧拖拽组件到画布</p>
              <p v-if="debugMode" style="font-size: 12px; color: #909399; margin-top: 8px;">
                或点击上方测试按钮添加组件
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <PropertyPanel 
        v-if="selectedComponent"
        :component="selectedComponent"
        @property-update="handlePropertyUpdate"
        @delete="handleComponentDelete"
        @copy="handleComponentCopy"
      />
      
      <!-- 未选择组件时的提示 -->
      <div v-else class="property-panel">
        <div class="panel-header">
          <h3>属性配置</h3>
        </div>
        <div class="panel-content">
          <div class="no-selection">
            <p>请选择一个组件来编辑其属性</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 拖拽管理器 -->
    <DragDropManager ref="dragDropManagerRef" />
  </div>
</template>

<script setup>
import { computed, ref, provide, watch, onMounted } from 'vue'
import { useDesignerStore } from '@/stores/designer'

import { useHistoryManager } from '@/composables/useHistoryManager'
import { widgetCategories } from '@/components/widgets'
import ComponentRenderer from './ComponentRenderer.vue'
import PropertyEditor from './PropertyEditor.vue'
import PropertyPanel from './PropertyPanel.vue'
import DragDropManager from './DragDropManager.vue'
import { 
  View, 
  Download, 
  Upload, 
  RefreshLeft, 
  RefreshRight 
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  projectId: {
    type: String,
    required: true
  }
})

// Emits
const emit = defineEmits([
  'save',
  'preview',
  'component-select',
  'component-update',
  'component-delete',
  'component-copy'
])

// Store
const designerStore = useDesignerStore()

// 历史记录管理器
const historyManager = useHistoryManager()

// DragDropManager 组件引用
const dragDropManagerRef = ref(null)

// 响应式状态
const selectedComponent = ref(null)
const zoomLevel = ref(1)
const currentPageIndex = ref(0)
const debugMode = ref(false)

// 拖拽状态引用 (将由DragDropManager组件管理)
const dragState = ref({
  isDragging: false,
  dragType: null,
  dragComponent: null,
  dragSource: null,
  dropTarget: null,
  dragPosition: { x: 0, y: 0 },
  dragOffset: { x: 0, y: 0 },
  dragStartTime: 0,
  dragStartPosition: { x: 0, y: 0 }
})

// 计算属性
const currentPage = computed(() => designerStore.currentPage)
const availableWidgets = computed(() => designerStore.availableWidgets)
const canUndo = computed(() => {
  // 优先检查 DragDropManager 的历史功能
  if (dragDropManagerRef.value && dragDropManagerRef.value.getHistory) {
    const history = dragDropManagerRef.value.getHistory()
    return history && history.currentIndex >= 0
  }
  return historyManager.canUndo.value
})

const canRedo = computed(() => {
  // 优先检查 DragDropManager 的历史功能
  if (dragDropManagerRef.value && dragDropManagerRef.value.getHistory) {
    const history = dragDropManagerRef.value.getHistory()
    return history && history.currentIndex < history.operations.length - 1
  }
  return historyManager.canRedo.value
})
const hasUnsavedChanges = computed(() => historyManager.hasUnsavedChanges.value)
const totalPages = computed(() => designerStore.currentProject?.pages?.length || 1)

// 初始化默认数据
if (!designerStore.currentProject) {
  designerStore.createProject('默认项目', '这是一个默认项目')
}
if (!designerStore.currentPage && designerStore.currentProject) {
  designerStore.createPage('页面1', '默认页面')
}

// 提供全局状态给子组件
provide('designerStore', designerStore)
provide('selectedComponent', selectedComponent)
provide('dragState', dragState)
provide('dragDropManager', dragDropManagerRef)
provide('historyManager', historyManager)
provide('debugMode', debugMode)

// 图标映射函数
const getWidgetIcon = (iconName) => {
  const iconMap = {
    'Document': 'Document',
    'Pointer': 'Pointer',
    'Picture': 'Picture',
    'Box': 'Box'
  }
  
  return iconMap[iconName] || 'Box'
}

// 获取组件属性
const getComponentProps = (component) => {
  const widget = Object.values(widgetCategories)
    .flat()
    .find(w => w.type === component.type)
  
  return widget?.propSchema || []
}

// 获取组件样式
const getComponentStyles = (component) => {
  const widget = Object.values(widgetCategories)
    .flat()
    .find(w => w.type === component.type)
  
  return widget?.styleSchema || []
}

// 获取画布项样式
const getCanvasItemStyle = (component) => {
  try {
    // 检查组件是否在容器内
    const parentId = designerStore.findParentId ? 
      designerStore.findParentId(designerStore.currentPage?.components || [], component.id) : 
      null
    const isInContainer = !!parentId
    
    // 如果在容器内，使用相对定位，让容器控制布局
    if (isInContainer) {
      return { position: 'relative' }
    }
    
    // 根层组件使用流式布局：相对定位 + 底部间距
    return { 
      position: 'relative',
      marginBottom: '8px' // 组件之间的间距
    }
  } catch (error) {
    console.warn('getCanvasItemStyle error:', error)
    // 出错时使用默认样式
    return { position: 'relative' }
  }
}

// 移除绝对定位计算函数，流式布局不需要
// const getNextStackPosition = () => { ... }

// 事件处理函数
const handleWidgetDragStart = (widget, event) => {
  const now = new Date().toISOString()
  const tempComponent = {
    id: `temp-${Date.now()}`,
    type: widget.type,
    name: `${widget.name}${Date.now()}`, // 设置一个唯一的默认名称
    props: { ...widget.defaultProps },
    style: { ...widget.defaultStyle },
    children: [],
    createdAt: now,
    updatedAt: now
  }
  
  console.log('🎯 创建拖拽组件:', { type: widget.type, name: tempComponent.name })
  
  // 使用 DragDropManager 组件的方法
  if (dragDropManagerRef.value) {
    dragDropManagerRef.value.handleDragStart(tempComponent, 'new', 'library', event)
  }
  
  // 添加拖拽样式
  event.target.classList.add('dragging')
}

const handleWidgetDragEnd = (event) => {
  // 移除拖拽样式
  event.target.classList.remove('dragging')
  
  // 使用 DragDropManager 组件的方法
  if (dragDropManagerRef.value) {
    dragDropManagerRef.value.handleDragEnd(event)
  }
}

const handleComponentSelect = (component) => {
  selectedComponent.value = component
  emit('component-select', component)
}

const handleComponentUpdate = (componentId, updates) => {
  // 处理组件更新
  if (updates.style) {
    designerStore.updateComponentStyle(componentId, updates.style)
  }
  if (updates.props) {
    designerStore.updateComponentProps(componentId, updates.props)
  }
  if (updates.children !== undefined) {
    // 更新子组件列表
    // 这里需要实现更新子组件的逻辑
    console.log('更新子组件:', componentId, updates.children)
  }
  
  emit('component-update', componentId, updates)
}

const handleComponentDelete = (componentId) => {
  const component = designerStore.getComponent(componentId)
  if (component) {
    // 记录历史
    historyManager.createDeleteRecord(component, {
      components: designerStore.currentPage.components
    })
    
    designerStore.removeComponent(componentId)
    if (selectedComponent.value?.id === componentId) {
      selectedComponent.value = null
    }
    emit('component-delete', componentId)
  }
}

const handleComponentDrop = (event, targetComponent = null) => {
  event.preventDefault()
  event.stopPropagation() // 阻止事件冒泡
  
  try {
    // 解析拖拽数据
    const dragData = JSON.parse(event.dataTransfer?.getData('application/json') || '{}')
    const { type, component, source } = dragData
    
    if (!type || !component) {
      console.error('❌ 拖拽数据无效:', dragData)
      return
    }
    
    // 计算放置位置 - 使用画布内容区域作为参考点
    const canvasContent = event.currentTarget.closest('.canvas-content')
    const rect = canvasContent ? canvasContent.getBoundingClientRect() : event.currentTarget.getBoundingClientRect()
    
    // 流式布局：不需要计算精确位置，组件会自然排列
    // 移除防重叠逻辑，因为流式布局不需要
    
    if (type === 'new') {
      // 判断是否根画布
      const isRoot = !targetComponent
      
      // 流式布局：不需要计算绝对位置，组件会自然排列
      const newComponent = {
        ...component,
        style: {
          ...component.style
          // 移除 left, top 等绝对定位属性
        }
      }
      
      if (targetComponent && targetComponent.type === 'container') {
        // 添加到容器组件
        const addedChild = designerStore.addChildComponent(targetComponent.id, newComponent)
        if (addedChild) {
          historyManager.createAddRecord(addedChild, {
            components: designerStore.currentPage.components
          })
        }
      } else {
        // 添加到页面根级别
        const addedComponent = designerStore.addComponent(newComponent)
        
        // 记录历史
        if (addedComponent) {
          historyManager.createAddRecord(addedComponent, {
            components: designerStore.currentPage.components.filter(c => c.id !== addedComponent.id)
          })
        }
      }
    } else if (type === 'move') {
      // 移动现有组件
      const previousPosition = { ...component.style }
      designerStore.moveComponent(component.id, targetComponent?.id)
      
      // 记录历史
      historyManager.createMoveRecord(component.id, previousPosition, component.style)
    }
    
  } catch (error) {
    console.error('拖拽数据解析失败:', error)
  } finally {
    // 重置拖拽状态 - 现在由 DragDropManager 组件处理
    if (dragDropManagerRef.value) {
      dragDropManagerRef.value.handleDragEnd(event)
    }
  }
}

  // 处理属性更新
  const handlePropertyUpdate = (componentId, propertyPath, value) => {
    console.log('123');
    console.log('🔧 属性更新:', { componentId, propertyPath, value, currentName: selectedComponent.value?.name })
    
    if (!componentId || !propertyPath) {
      console.warn('❌ 属性更新失败: 缺少必要参数')
      return
    }
    
    try {
      // 解析属性路径
      if (propertyPath.startsWith('props.')) {
        // 处理组件属性更新
        const propKey = propertyPath.replace('props.', '')
        const updates = { props: { [propKey]: value } }
        
        console.log('🔧 更新组件属性-props:', { componentId, propKey, value, updates })
        designerStore.updateComponentProps(componentId, { [propKey]: value })
        
      } else if (propertyPath === 'name') {
        // 处理组件名称更新
        console.log('🔧 更新组件名称:', { componentId, value })
        designerStore.updateComponent(componentId, { name: value })
        
      } else if (propertyPath === 'style') {
        // 处理样式更新
        console.log('🔧 更新组件样式:', { componentId, value })
        designerStore.updateComponentStyle(componentId, value)
        
      } else {
        // 其他属性直接更新
        console.log('🔧 更新其他属性:', { componentId, propertyPath, value })
        designerStore.updateComponent(componentId, { [propertyPath]: value })
      }
      
      console.log('✅ 属性更新完成')
      
    } catch (error) {
      console.error('❌ 属性更新失败:', error)
    }
  }

const handleComponentCopy = (componentId) => {
  const component = designerStore.getComponent(componentId)
  if (component) {
    const newComponent = {
      ...component,
      id: `comp-${Date.now()}`,
      name: `${component.name || component.type}_副本`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    designerStore.addComponent(newComponent)
    emit('component-copy', newComponent)
  }
}

const handleUndo = () => {
  // 优先使用 DragDropManager 的撤销功能
  if (dragDropManagerRef.value && dragDropManagerRef.value.undoOperation) {
    dragDropManagerRef.value.undoOperation()
  } else {
    // 备用：使用历史管理器
    const result = historyManager.undo()
    if (result) {
      // 根据历史记录恢复状态
      applyHistoryChange(result)
    }
  }
}

const handleRedo = () => {
  // 优先使用 DragDropManager 的重做功能
  if (dragDropManagerRef.value && dragDropManagerRef.value.redoOperation) {
    dragDropManagerRef.value.redoOperation()
  } else {
    // 备用：使用历史管理器
    const result = historyManager.redo()
    if (result) {
      // 根据历史记录恢复状态
      applyHistoryChange(result)
    }
  }
}

const applyHistoryChange = (historyResult) => {
  const { record, action, previousState, newState } = historyResult
  
  switch (record.type) {
    case 'add':
      if (action === 'undo') {
        // 撤销添加：删除组件
        designerStore.removeComponent(record.componentId)
      } else {
        // 重做添加：恢复组件
        designerStore.addComponent(newState.component)
      }
      break
      
    case 'delete':
      if (action === 'undo') {
        // 撤销删除：恢复组件
        designerStore.addComponent(previousState.component)
      } else {
        // 重做删除：删除组件
        designerStore.removeComponent(record.componentId)
      }
      break
      
    case 'style':
      if (action === 'undo') {
        // 撤销样式修改：恢复之前的样式
        designerStore.updateComponentStyle(record.componentId, previousState.style)
      } else {
        // 重做样式修改：应用新样式
        designerStore.updateComponentStyle(record.componentId, newState.style)
      }
      break
      
    case 'props':
      if (action === 'undo') {
        // 撤销属性修改：恢复之前的属性
        designerStore.updateComponentProps(record.componentId, previousState.props)
      } else {
        // 重做属性修改：应用新属性
        designerStore.updateComponentProps(record.componentId, newState.props)
      }
      break
      
    case 'move':
      if (action === 'undo') {
        // 撤销移动：恢复之前的位置
        designerStore.updateComponentStyle(record.componentId, previousState.position)
      } else {
        // 重做移动：应用新位置
        designerStore.updateComponentStyle(record.componentId, newState.position)
      }
      break
  }
}

const handleSave = () => {
  emit('save', designerStore.currentProject)
}

const handlePreview = () => {
  emit('preview', designerStore.currentProject)
}

const handleExport = () => {
  // TODO: 实现导出逻辑
  console.log('导出项目:', designerStore.currentProject)
}

const handleZoomChange = (newZoom) => {
  zoomLevel.value = newZoom
  emit('zoom-change', newZoom)
}

const handlePageChange = (pageIndex) => {
  currentPageIndex.value = pageIndex
  emit('page-change', pageIndex)
}

const handleHistoryAction = (action) => {
  if (action.action === 'go-to' && action.index !== undefined) {
    const result = historyManager.goToHistory(action.index)
    if (result) {
      applyHistoryChange(result)
    }
  } else if (action.action === 'clear') {
    historyManager.clearHistory()
  }
}

// 新增的方法
const clearCanvas = () => {
  if (currentPage.value) {
    currentPage.value.components = []
    clearSelection()
  }
}

const clearSelection = () => {
  selectedComponent.value = null
}

const editComponent = (component) => {
  // TODO: 实现编辑逻辑
  console.log('编辑组件:', component)
}

const isComponentSelected = (component) => {
  return selectedComponent.value?.id === component.id
}

// 拖拽相关方法
const handleComponentDragStart = (component, event) => {
  // 设置拖拽数据
  event.dataTransfer.setData('dragType', 'move')
  event.dataTransfer.setData('componentId', component.id)
  event.dataTransfer.setData('componentType', component.type)
  
  // 使用 DragDropManager 组件的方法
  if (dragDropManagerRef.value) {
    dragDropManagerRef.value.handleDragStart(component, 'move', 'canvas', event)
  }
  
  // 添加拖拽样式
  event.target.classList.add('dragging')
}

const handleComponentDragEnd = (event) => {
  // 移除拖拽样式
  event.target.classList.remove('dragging')
  
  // 使用 DragDropManager 组件的方法
  if (dragDropManagerRef.value) {
    dragDropManagerRef.value.handleDragEnd(event)
  }
}

const handleComponentDragOver = (event, targetComponent) => {
  event.preventDefault()
  
  // 通知 DragDropManager 拖拽移动
  if (dragDropManagerRef.value) {
    dragDropManagerRef.value.handleDragMove(event)
  }
  
  // 如果是容器组件，显示可拖拽的视觉提示
  if (targetComponent && targetComponent.type === 'container') {
    const containerElement = event.currentTarget
    containerElement.classList.add('drag-over')
  }
}

const handleComponentDragLeave = (event) => {
  // 移除拖拽高亮
  const containerElement = event.currentTarget
  containerElement.classList.remove('drag-over')
}

// 处理拖拽目标高亮
const handleDragTargetHighlight = (targetComponent) => {
  // 清除之前的高亮
  document.querySelectorAll('.drag-target-highlight').forEach(el => {
    el.classList.remove('drag-target-highlight')
  })
  
  // 为当前拖拽目标添加高亮
  if (targetComponent) {
    const targetElement = document.querySelector(`[data-component-id="${targetComponent.id}"]`)
    if (targetElement) {
      targetElement.classList.add('drag-target-highlight')
    }
  }
}

const handleDragOver = (event) => {
  event.preventDefault()
  
  // 通知 DragDropManager 拖拽移动
  if (dragDropManagerRef.value) {
    dragDropManagerRef.value.handleDragMove(event)
  }
  
  // 确保画布可以接受拖拽
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'copy'
  }
}

const handleDragLeave = (event) => {
  // 清除拖拽高亮效果
  document.querySelectorAll('.drag-over').forEach(el => {
    el.classList.remove('drag-over')
  })
}

const handleDragEnter = (event) => {
  event.preventDefault()
  
  // 确保画布可以接受拖拽
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'copy'
  }
}

// 测试方法
const testAddComponent = () => {
  if (debugMode.value) {
    console.log('🧪 开始测试添加组件功能...')
  }
  
  if (!currentPage.value) {
    return
  }
  
  const now = new Date().toISOString()
  // 创建一个测试文本组件
  const testComponent = {
    id: `test_comp_${Date.now()}`,
    type: 'text',
    name: '测试文本组件',
    props: {
      name: '测试文本组件',
      text: '这是一个测试文本组件',
      fontSize: 16,
      color: '#409eff',
      fontWeight: 'bold',
      textAlign: 'center'
    },
    style: {
      padding: '16px',
      margin: '16px',
      backgroundColor: '#f0f9ff',
      border: '1px solid #409eff',
      borderRadius: '8px'
    },
    children: [],
    events: {},
    data: {},
    createdAt: now,
    updatedAt: now
  }
  
  try {
    designerStore.addComponent(testComponent)
    if (debugMode.value) {
      console.log('✅ 测试组件添加成功')
    }
  } catch (error) {
    if (debugMode.value) {
      console.error('❌ 测试组件添加失败:', error)
    }
  }
}

const testDragAndDrop = () => {
  if (debugMode.value) {
    console.log('🧪 开始测试拖拽功能...')
  }
  
  // 测试拖拽事件监听器
  const canvasContent = document.querySelector('.canvas-content')
  if (canvasContent) {
    if (debugMode.value) {
      console.log('🧪 检查画布拖拽事件监听器...')
    }
  }
}

// 生命周期
onMounted(() => {
  if (debugMode.value) {
    console.log('🚀 DesignerCore 组件已挂载')
  }
})
</script>

<style scoped>
.designer-core {
  height: 100vh;
  min-width: 1200px; /* 添加最小宽度，确保布局稳定 */
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.designer-header {
  height: 56px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  margin-bottom: 10px;
}

.header-left h1 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.header-center {
  display: flex;
  gap: 8px;
}

.header-right {
  display: flex;
  gap: 8px;
}

.designer-main {
  flex: 1;
  display: flex;
  overflow: hidden;
  padding: 0 10px;
  gap: 10px;
  min-width: 1180px; /* 确保主区域有足够的最小宽度 */
}

.component-library {
  width: 240px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.library-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.library-header h3 {
  margin: 0;
  font-size: 15px;
  color: #303133;
  font-weight: 600;
}

.library-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.category-section {
  margin-bottom: 16px;
}

.category-section:last-child {
  margin-bottom: 0;
}

.category-title {
  font-weight: 600;
  color: #606266;
  margin-bottom: 8px;
  font-size: 14px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.widget-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.widget-item {
  padding: 12px 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  text-align: center;
  cursor: grab;
  transition: all 0.2s ease;
  background: white;
}

.widget-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
  transform: translateY(-1px);
}

.widget-item:active {
  cursor: grabbing;
  transform: translateY(0);
}

.widget-item.dragging {
  opacity: 0.5;
  transform: scale(0.95);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  cursor: grabbing;
}

.widget-icon {
  font-size: 20px;
  color: #409eff;
  margin-bottom: 6px;
}

.widget-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.widget-name {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  line-height: 1.2;
}

.widget-description {
  font-size: 10px;
  color: #909399;
  margin-top: 2px;
  line-height: 1.2;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.design-canvas {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.canvas-header {
  padding: 12px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafafa;
}

.canvas-header span {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.canvas-tools {
  display: flex;
  gap: 6px;
}

.canvas-content {
  flex: 1;
  padding: 16px;
  padding-top: 16px; /* 减少顶部内边距，因为标签现在在边框上 */
  overflow: auto;
  position: relative;
  min-height: 600px;
}

.canvas-component {
  position: relative;
  display: inline-block;
  transition: all 0.15s ease;
}

.canvas-component:last-child {
  margin-bottom: 0;
}

.canvas-component.is-selected {
  outline: 2px solid #409eff;
  outline-offset: 2px;
  border-radius: 4px;
}

.canvas-component[draggable="true"] {
  cursor: grab;
}

.canvas-component[draggable="true"]:active {
  cursor: grabbing;
}

.canvas-component.dragging {
  opacity: 0.6;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.2s ease;
}

/* 拖拽高亮效果 */
.canvas-component.drag-over,
.container-widget.drag-over,
.component-wrapper.drag-over {
  border: 2px dashed #409eff !important;
  background-color: rgba(64, 158, 255, 0.05) !important;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3) !important;
  transition: all 0.15s ease !important;
}

/* 容器组件的拖拽高亮效果 */
.container-widget.drag-over {
  background-color: rgba(64, 158, 255, 0.1) !important;
}

/* 组件包装器的拖拽高亮效果 */
.component-wrapper.drag-over {
  background-color: rgba(64, 158, 255, 0.08) !important;
}

/* 确保拖拽样式优先级 */
.canvas-component.dragging {
  opacity: 0.6 !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  transition: all 0.2s ease !important;
}

/* 拖拽悬停时的容器样式 */
.container-widget:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.02);
  transition: all 0.15s ease;
}

/* 防止拖拽时的布局抖动 */
.canvas-component {
  position: relative;
  margin-bottom: 12px;
  transition: all 0.15s ease;
}

/* 拖拽高亮时的边框保持 */
.canvas-component.drag-over,
.container-widget.drag-over {
  border: 2px dashed #409eff !important;
  border-radius: 4px;
  box-sizing: border-box;
}

/* 调试工具样式 */
.debug-tools {
  position: sticky;
  top: 0;
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid #409eff;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 16px;
  z-index: 100;
}

.debug-tools .el-button {
  font-size: 12px;
}

/* 空画布拖拽提示 */
.empty-canvas {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
  transition: all 0.2s ease;
}

.empty-canvas:hover {
  background-color: rgba(64, 158, 255, 0.05);
  border: 2px dashed #409eff;
  border-radius: 8px;
}

/* 空画布拖拽悬停时的样式 */
.empty-canvas.drag-over {
  background-color: rgba(64, 158, 255, 0.1) !important;
  border: 2px dashed #409eff !important;
  border-radius: 8px;
  box-shadow: 0 0 12px rgba(64, 158, 255, 0.3);
  transition: all 0.2s ease;
}

.empty-canvas .empty-tip {
  text-align: center;
  padding: 20px;
}

.empty-canvas .empty-tip i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-canvas .empty-tip p {
  margin: 0;
  color: #909399;
}

/* 拖拽悬停时的画布样式 */
.canvas-content:hover {
  background-color: rgba(64, 158, 255, 0.05);
}

.canvas-content.drag-over {
  background-color: rgba(64, 158, 255, 0.1);
  border: 2px dashed #409eff;
}

/* 组件库拖拽项样式 */
.widget-item {
  cursor: grab;
  transition: all 0.2s ease;
}

.widget-item:hover {
  background-color: #f5f7fa;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.widget-item:active {
  cursor: grabbing;
}

.property-panel {
  width: 280px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.panel-header h3 {
  margin: 0;
  color: #303133;
  font-size: 15px;
  font-weight: 600;
}

.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.component-properties > * + * {
  margin-top: 20px;
}

.property-section {
  margin-bottom: 20px;
}

.property-section:last-child {
  margin-bottom: 0;
}

.property-section h4 {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
  padding-bottom: 6px;
  border-bottom: 1px solid #f0f0f0;
}

.property-item {
  margin-bottom: 12px;
}

.property-item:last-child {
  margin-bottom: 0;
}

.property-item label {
  display: block;
  margin-bottom: 6px;
  color: #606266;
  font-size: 12px;
  font-weight: 500;
}

/* 组件名称区域特殊样式 */
.component-name-section {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 24px;
  border: 1px solid #e9ecef;
}

.component-name-section h4 {
  color: #409eff;
  border-bottom-color: #409eff;
}

.property-description {
  display: block;
  margin-top: 4px;
  color: #909399;
  font-size: 11px;
  line-height: 1.4;
}

.no-selection {
  text-align: center;
  color: #909399;
  padding: 30px 20px;
}

.no-selection p {
  margin: 0;
  font-size: 14px;
}

/* 拖拽目标高亮样式 */
.drag-target-highlight {
  position: relative;
  z-index: 1000;
}

.drag-target-highlight::after {
  content: '';
  position: absolute;
  top: -6px;
  left: -6px;
  right: -6px;
  bottom: -6px;
  border: 3px solid #67c23a;
  border-radius: 8px;
  background: rgba(103, 194, 58, 0.1);
  pointer-events: none;
  z-index: 999;
}

/* 响应式布局 - 保持固定水平布局 */
@media (max-width: 1200px) {
  /* 保持水平布局，不改变方向 */
  .designer-main {
    flex-direction: row;
  }
  
  /* 保持固定宽度，不改变布局 */
  .component-library,
  .property-panel {
    width: auto;
    height: auto;
  }
}
</style>
